package com.nmsl.statistic.thirdController;


import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;

import com.nmsl.common.core.domain.entity.SysDictData;
import com.nmsl.common.utils.uuid.UUID;
import com.nmsl.statistic.constants.Constants;
import com.nmsl.statistic.domain.RetailMedicine;
import com.nmsl.statistic.domain.TollManage;
import com.nmsl.statistic.mapper.DailyFlowMapper;
import com.nmsl.statistic.mapper.RetailMedicineMapper;
import com.nmsl.statistic.mapper.TollManageMapper;
import com.nmsl.statistic.utils.DailyFlowUtils;
import com.nmsl.statistic.utils.RedisUtil;
import io.netty.util.Constant;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private TollManageMapper tollManageMapper;

    @Autowired
    private RetailMedicineMapper retailMedicineMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DailyFlowMapper dailyFlowMapper;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";
    private String appId = "9021000140657253";
    private String appPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZOaOELih4Ml/yqs1HNRekIxZPBwqfhsUbdjhPDJ2jlunafQvauavfkCZeGaPrGRpnzXFKp5UxvlXwgP4UWJ6KwWguNu9eT/fYR70vcMAI5nQaLnBIVxSmWX+70ZSaj/Q35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5hFJUJpwq3dAoGBAIyAhUBbrSEyKTIR92PsFXyfDqC4zxuGp/XnKTEmIkmAhXS8v/3BJB+sIomZhkiFTlGneYWi9Dumw8aLxwtvQ834ssObSSTYmalPG/w9OJqpXI/hFx7GFypZp/hGNzC8umcaPXozWqTsCI0qfhGL4C7D57Vnzrv9BYq9oWbWSFjpAoGBANNH5s9bsF1OF8NMyQY0g4040C9mxkqjLcD/5p/7ZTdiaWOvyqd6Rj2/9yJXnd+qRnZw89vWz2Oq+FSp2J3aoBwYvYcY3umavRuIIfwaJ2I1Wx+Ej8Bwhvniwxm3DAP1E18JZAVdeQKBYuY44I3i4N1gs7bpvSHA/BveyolQwtti";
    private String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOuqfn2NqMiopyXXKtuFC05XfEE2RRmu/sSsZBQgSxHL/+lXZVG/pU8IJm6qoTVeXKG3CjGN3jCfKyJWKBsnxI15mc/hIktPpqAXSy90rxHiEJh8xi7bV3GNLOPf/7DZno1Hvqk/K+J/bCjb1xrMW7trhokJYfLQjiaFA5KoCzl9EF0wPvnWEatthxzZYsixpy4JmggJqtumsLmTeG68w2m1NjgjPbnp7N7rqbo4w2PYA9lI6i/z26dOKWfxTta+iDS7kyATI8a6eCVNw6t6zlm5c/nb5oXiVEztyReEKQIbYnNl6KUJ/+PWgR7sTwty220pClwpu6qE57mU1Qis+QIDAQAB";
    private String notifyUrl  = "http://4a2770v720.vicp.fun/api/alipay/notify";
//    @Resource
//    private AliPayConfig aliPayConfig;


    @RequestMapping("/pay/{tollManageId}")
    public void pay(@PathVariable(value = "tollManageId") String order, HttpServletResponse httpServletResponse) throws Exception {

        System.out.println("nmsl");
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                appId,
                appPrivateKey,
                FORMAT,
                CHARSET,
                alipayPublicKey,
                SIGN_TYPE
        );

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        JSONObject bizCOntent = new JSONObject();
        TollManage tollManage = tollManageMapper.selectTollManageByTollManageId(Long.parseLong(order));
//        修改订单状态
        tollManage.setStatus("1");
        tollManage.setPayType("支付宝");
        tollManageMapper.updateTollManage(tollManage);
//        药品销量增加
        String orderId = tollManage.getOrderId();
        String orderType = tollManage.getOrderType();
        String key = orderType.equals("1") ? Constants.medicinesRetailRanking : Constants.medicinesRecipeRanking;
//        查询绑定药品信息  定时任务持久化
        List<RetailMedicine> list = retailMedicineMapper.selecetByRetailOrderId(Long.valueOf(orderId));

        for (RetailMedicine item : list) {
            RedisUtil.updataMedicinesRanking(redisTemplate,key,item.getMedicineId(),item.getMedicineNum().intValue());
            RedisUtil.updataMedicinesRanking(redisTemplate,Constants.medicinesRanking,item.getMedicineId(),item.getMedicineNum().intValue());
        }
//        计算每日流水
        DailyFlowUtils.pay(dailyFlowMapper,tollManage,redisTemplate);
        bizCOntent.put("out_trade_no",order);
        bizCOntent.put("total_amount", tollManage.getAmount()+"");
        bizCOntent.put("subject", "测试");
        bizCOntent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizCOntent.toString());
        // 支付宝异步回调
        request.setReturnUrl("http://localhost:85/retail");
        request.setNotifyUrl("http://4a2770v720.vicp.fun:13743/alipay/notify");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpServletResponse.setContentType("text/html;charset=" + CHARSET);
        httpServletResponse.getWriter().write(form);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        String sign = "";
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                System.out.println(name);
                params.put(name, request.getParameter(name));
                if (name.equals("sign")){
                    sign =request.getParameter(name);
                    System.out.println(sign);
                }

            }
            System.out.println(params);
            // 支付宝验签
            String content = AlipaySignature.getSignCheckContentV1(params);
            System.out.println( params.get("gmt_create"));
//            boolean checkSignature = AlipaySignature.
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, "UTF-8");
            if (checkSignature) {
//                System.out.println("success");
//                System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

//                 更新订单未已支付
//                ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);
            }
        }
        return "success";
    }

}
